<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul v-for="cartInfo in cartInfoList" :key="cartInfo.id" class="cart-list">
          <li class="cart-list-con1">
            <input :checked="!!cartInfo.isChecked" @change="checkCartInfoState(cartInfo)" type="checkbox" name="chk_list">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg" @click="$router.push(`/detail/${cartInfo.skuId}`)">{{cartInfo.skuName}}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{cartInfo.skuPrice}}</span>
          </li>
          <li class="cart-list-con5">
            <a @click="btnAddCartInfo(cartInfo, -1, $event)" href="javascript:void(0)" class="mins">-</a>
            <input autocomplete="off" type="text" @input="checkNum($event, cartInfo)" :value="cartInfo.skuNum" minnum="1" class="itxt">
            <a @click="btnAddCartInfo(cartInfo, 1, $event)" href="javascript:void(0)" class="plus">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{cartInfo.cartPrice * cartInfo.skuNum}}</span>
          </li>
          <li class="cart-list-con7">
            <a @click="deleteCart(cartInfo.skuId)"  href="javascript:;" class="sindelet">删除</a>
            <br>
            <a href="javascript:;">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input v-model="checkAll" class="chooseAll" type="checkbox">
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="deleteAllCart" href="javascript:;">删除选中的商品</a>
        <a href="javascript:;">移到我的关注</a>
        <a href="javascript:;">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{cartInfoList.reduce((pre, item)=>item.isChecked ? pre + 1: pre, 0)}}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{cartInfoList.reduce((pre, item)=>item.isChecked ? pre + item.skuPrice * item.skuNum : pre, 0)}}</i>
        </div>
        <div class="sumbtn">
          <a @click="submitbalance">结算</a>
        </div>
      </div>
    </div>

    <!-- 确认对话框 -->
    <Confirm :visible.sync="visible" title="删除提示" :oncancel="oncancel" :onfinish="onfinish">
      <template>
        确认删除商品信息？
      </template>
    </Confirm>
  </div>
</template>

<script>
import { reqGetCartList, reqGetUpdateCheckCart,reqAddToCard, reqDeleteCart } from '@/apis';
import { skuNumReg } from '@/utils/reg';
// import debounce from '@/utils/debounce'
import {v4 as uuidv4} from 'uuid'
  export default {
    name: 'ShopCart',
    data(){
      return {
        cartInfoList: [],
        timer: null,
        visible: false,
        willDelete: undefined,
      }
    },
    methods: {
      async getShopCartList(){
        const res = await reqGetCartList()

        res.code == 200 && res.data?.length != 0 ? (this.cartInfoList = res.data[0].cartInfoList) : console.log(res.message)
      },
      // 改变选中状态
      async checkCartInfoState(cartInfo){
        const res = await reqGetUpdateCheckCart(cartInfo.skuId, 1-cartInfo.isChecked)
        if(res.code == 200) {
          cartInfo.isChecked = 1-cartInfo.isChecked
        }
      },
      // 加/减数量
      async addCartInfo(skuInfo, count) {
        const res = await reqAddToCard(skuInfo.skuId, count)
        if(res.code == 200) {
          skuInfo.skuNum += count
        }
      },
      // 加/减 事件处理
      btnAddCartInfo(skuInfo, count, e){
        clearTimeout(this.timer)

        const input = count > 0 ? e.target.previousElementSibling : e.target.nextElementSibling
        input.value = +input.value + count
        // 若验证不通过, 则恢复初始值
        if(!skuNumReg.test(input.value)) {
          input.value = skuInfo.skuNum
          return 
        }

        this.timer = setTimeout(() => {
          this.addCartInfo(skuInfo, input.value - skuInfo.skuNum)
        }, 500);
      }
      // debounce(function(skuInfo, count){
      //   this.addCartInfo(skuInfo.skuId, )
      // })
      ,
      // 输入的时候校验数量是否合规
      checkNum(e, skuInfo){
        clearTimeout(this.timer)
        const {value} = e.target
          if(skuNumReg.test(value)){ 
            // 验证通过
            // 把差值发送给服务器
            this.timer = setTimeout(() => {
              this.addCartInfo(skuInfo, value - skuInfo.skuNum)
            }, 500);
          } else {
            // 验证不通过，则恢复原值
            e.target.value = skuInfo.skuNum
          }
      },
      // 删除购物车中的单个商品
      deleteCart (skuId){
        // 弹出确认删除对话框
        this.visible = true
        this.willDelete = skuId
      },
      // 删除全部选中的商品
      deleteAllCart (){
        // 弹出确认删除对话框
        this.visible = true
        // 先过滤出来已经选中的，再把 skuId 提取出来
        this.willDelete = this.cartInfoList.filter(item => item.isChecked).map(item => item.skuId)
      },
      // 确认框-确定
      async onfinish(){
        this.visible = false
        // 如果是删除单个商品
        if(!Array.isArray(this.willDelete)) {
          // 请求删除
          const res = await reqDeleteCart(this.willDelete)
          // 删除成功
          if(res.code == 200) {
            // 删除购物车中的对应数据，
            this.cartInfoList = this.cartInfoList.filter(item => item.skuId != this.willDelete)
          } else {
            alert('删除失败，请稍后重试！')
          }
        } else { // 删除多个商品
          const pros = this.willDelete.map(skuId => reqDeleteCart(skuId))
          // 所有的都删除成功了才会成功
          Promise.all(pros).then(res => {
            // 删除购物车中的对应数据，
            this.cartInfoList = this.cartInfoList.filter(item => !this.willDelete.includes(item.skuId))

          }).catch(error=> alert('删除失败！请稍后重试'))
        }
      },
      // 确认框-取消
      oncancel(){
        // 关闭提示对话框
        this.visible = false
      },
      submitbalance(){
        this.$router.push('/trade')
      }
    },
    computed: {
      checkAll: {
        get(){
          return this.cartInfoList.every(item=>item.isChecked)
        },
        set(value){
          let checked = value?1:0
          this.cartInfoList.forEach(item => {
            reqGetUpdateCheckCart(item.skuId, checked)
            item.isChecked = checked
          })
        }
      }
    },
    async mounted(){
      this.getShopCartList()
    },
    
  }

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
            cursor: pointer;
          }
          .item-msg:hover {
            color: #333
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }
			

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>